package com.dongdongshop.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.core.Result;
import com.dongdongshop.core.ResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.user.TbUser;
import com.dongdongshop.service.user.UserService;
import com.dongdongshop.utils.JavaMailUtil;
import com.dongdongshop.utils.ShiroUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
@RequestMapping("user")
public class UserController {

    Logger logger = LoggerFactory.getLogger(UserController.class);

    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Reference
    private UserService userService;

    //进入主页
    @RequestMapping("index")
    public String index(){
        return "/";
    }

    //登录成功
    @RequestMapping("index1")
    public String index1(){
        return "index";
    }

    //跳转注册页
    @RequestMapping("toRegister")
    public String toRegister(){
        return "register";
    }

    //跳转登录页
    @RequestMapping("toLogin")
    public String toLogin(){
        return "login";
    }

    //发送短信消息
    @RequestMapping("/sendMessage")
    @ResponseBody
    public Result sendMessage(String phoneNumber) {
        try {
            String message = userService.sendMessage(phoneNumber);
            return Result.response(ResultEnum.SUCCESS).setData(message);
        } catch (Exception e) {
            logger.error("发送消息失败: {}", e);
            return Result.response(ResultEnum.ERROR);
        }
    }

    //注册
    @RequestMapping("/register")
    @ResponseBody
    public Result register(TbUser user, String code) {
        try {
            //判断用户是否存在
            TbUser u = userService.getUserByUserName(user.getUsername());
            if (u != null){
                return Result.response(ResultEnum.SUCCESS).setData("用户存在");
            }
            //获取用的验证码进行对比
            String vocode = (String)redisTemplate.boundValueOps(user.getPhone()).get();
            //首先我对缓存设置了有效时间
            if (vocode == null || !vocode.equals(code)){
                return Result.response(ResultEnum.SUCCESS).setData("验证码不对或过有效期");
            }
            //调用进行用户注册
            //生成盐拿到盐之后进行生成密文
            String salt = ShiroUtils.generateSalt(6);
            String password = ShiroUtils.encryptPassword("MD5", user.getPassword(), salt, 10);
            user.setSalt(salt);
            user.setPassword(password);
            user.setCreated(new Date());
            user.setUpdated(new Date());
            userService.addUser(user);

            return Result.response(ResultEnum.SUCCESS).setData("success");
        } catch (Exception e) {
            logger.error("注册出现异常: {}", e);
            return Result.response(ResultEnum.ERROR);
        }
    }

    //登录
    @RequestMapping("/login")
    public String login(TbUser user, Model model) {
        //根据用户名查询数据库
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(),user.getPassword());
        try {
            subject.login(token);
        }catch (UnknownAccountException e){
            model.addAttribute("msg","用户不存在或者未通过审核");
            logger.error("当前用户不存在,{}",e);
            return "login";
        }catch (IncorrectCredentialsException e){
            logger.error("密码不正确,{}",e);
            model.addAttribute("msg","密码不正确");
            return "login";
        }
        return "redirect:/";
    }
    /*
    * 获取当前登录的用户信息
    * */
    @RequestMapping("getLoginUserInfo")
    @ResponseBody
    public DataResult getLoginUserInfo(){
        TbUser user = null;
        try {
            user = (TbUser)SecurityUtils.getSubject().getPrincipal();
        }catch (Exception e){
            logger.error("获取用户信息异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage(),user);
    }

    @RequestMapping("updatePwd")
    @ResponseBody
    public Result updatePwd(TbUser user,String phone,String code){

        String password = user.getPassword();
        try {
            String phone1 = user.getPhone();
            Boolean b = userService.checkCodeByPhone(user.getPhone(),code);

            if (b == false){
                return Result.response(ResultEnum.ERROR).setData("验证码错误");
            }

            TbUser byUser = userService.getByUser(user.getId());
            Optional<TbUser> byUser1 = Optional.ofNullable(byUser);
            if (byUser1.isPresent()){
                return Result.response(ResultEnum.ERROR);
            }
            String salt = ShiroUtils.generateSalt(6);
            String md5 = ShiroUtils.encryptPassword("MD5", user.getPassword(), salt, 10);
            user.setSalt(salt);
            user.setPassword(md5);
            //判断用户存不存在
            List<TbUser> user1 = userService.getByName(user.getUsername());

            if(phone1 != phone){
                return Result.response(ResultEnum.ERROR).setData("请输入注册时使用的手机号码");
            }

            if (user1.size() == 0 ){
                return Result.response(ResultEnum.ERROR).setData("用户不存在");
            }

            TbUser tbUser = user1.get(0);
            Long id = tbUser.getId();
            user.setId(tbUser.getId());

            logger.info("修改成功");
            userService.updatePwdandSalt(user);

            email(id,password);
            return Result.response(ResultEnum.SUCCESS).setData("重置密码成功，密码以发至您的邮箱，请注意查收");
        }catch (Exception e){
            logger.error("系统错误",e);
            return Result.response(ResultEnum.ERROR).setData("操作失败");
        }
    }

    public void  email(Long id,String password) throws Exception {
        JavaMailUtil javaMailUtil = new JavaMailUtil();
        //发件人的地址
        String send = "tyz631116@163.com";
        //获取当前账户的id用来获取email
        TbUser user = userService.getByUser(id);
        //正文信息
        String content = "您的密码为："+ password;
        //收件人地址
        String direction = user.getEmail();

        javaMailUtil.javaMail(send,content,direction);
    }
}